package com.abc.xxx.util;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Getter
@Setter
public class Result {

    private String oper;
    private boolean succ = true;
    private String type;
    private String msg;
    private Map<String, Object> result = new HashMap<>();

    //================ 构造函数

    public Result(String oper, boolean succ, String type, String msg) {
        this.oper = oper;
        this.succ = succ;
        this.type = type;
        this.msg = msg;
    }

    public Result(String oper, boolean succ, String type, String msg, String dataKey, String dataValue) {
        this.oper = oper;
        this.succ = succ;
        this.type = type;
        this.msg = msg;
        this.result.put(dataKey, dataValue);
    }

    //================ 静态工厂方法

    public static Result success(String oper) {
        return new Result(oper, true, "success", null);
    }

    public static Result warning(String oper) {
        return new Result(oper, false, "warning", null);
    }

    public static Result error(String oper) {
        return new Result(oper, false, "error", null);
    }

    //================ 链式调用方法

    public Result msg(String msg) {
        this.msg = msg;
        return this;
    }

    public Result type(String type) {
        this.type = type;
        return this;
    }

    public Result data(String dataKey, Object dataValue) {
        this.result.put(dataKey, dataValue);
        return this;
    }

    public Result obj(Object obj){
        this.result.put("obj", obj);
        return this;
    }

    public Result list(List list){
        this.result.put("list", list);
        return this;
    }

    public Result page(IPage page){
        this.result.put("current", page.getCurrent());
        this.result.put("size", page.getSize());
        this.result.put("total", page.getTotal());
        this.result.put("list", page.getRecords());
        return this;
    }

    //================ 其它便捷方法

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
